import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr

from celery import Celery

# 邮件相关配置
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 25
# 发送邮件的邮箱
EMAIL_HOST_USER = 'sunchaoyi314@163.com'
# 在邮箱中设置的客户端授权密码
EMAIL_HOST_PASSWORD = '584217zz'
# 收件人看到的发件人
EMAIL_FROM = '美多商城<sunchaoyi314@163.com>'

app = Celery(
    'celery_email',  # 当前模块的名字
    broker='amqp://guest@localhost//',  # 消息队列的url
    backend='redis://localhost:6379/5'  # 将调用的结果存储到Redis中
)


# 中文处理
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


@app.task
def send_email(receivers, body_content, subject, mail_from=None):
    message = MIMEText(body_content, 'html', 'utf-8')
    message['From'] = _format_addr(EMAIL_FROM if not mail_from else mail_from)  # 显示的发件人
    message['To'] = ','.join(receivers)
    message['Subject'] = Header(subject, 'utf-8')
    smtp_obj = smtplib.SMTP()
    smtp_obj.connect(EMAIL_HOST, EMAIL_PORT)
    smtp_obj.set_debuglevel(1)
    smtp_obj.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
    smtp_obj.sendmail(EMAIL_FROM, receivers, message.as_string())
    smtp_obj.quit()


if __name__ == '__main__':
    send_email(['1822569745@qq.com'], '<p>辛苦了</p>', '王老师的信')
